layui.use(['form', 'layedit', 'laydate', 'table', 'laytpl', 'jquery'], function () {
    var form = layui.form
        , layer = layui.layer
        , layedit = layui.layedit
        , table = layui.table
        , laydate = layui.laydate
        , laytpl = layui.laytpl
        , $ = layui.jquery
        , laydate = layui.laydate;
    // var addIndex; // 新增窗口索引
    var addMenuHtml;
    //日期时间范围
    laydate.render({
        elem: '#queryTime'
        , type: 'datetime'
        , range: true
        , max: 'nowTime'
        , min: '2018-07-01'
    });
    //渲染表单
    form.render();
    //查询列表渲染
    var menuPermission = table.render({
        elem: '#test'
        , url: '/user/userList'
        , toolbar: '#toolbarDemo'
        , title: '菜单列表'
        , totalRow: false
        , contentType: 'application/json'
        , method: 'post'
        , sort: true
        , cols: [[
            {type: 'checkbox', fixed: 'left'}
            , {field: 'userId', title: '用户ID', width: 90, sort: true}
            , {field: 'userName', title: '用户姓名', width: 150}
            // , {field: 'CATEGORY_ID', title: '父级菜单名称', width: 150, templet: '#categoryId'}
            , {field: 'phoneNumber', title: '用户电话', width: 120}
            , {field: 'nickName', title: '用户昵称', width: 120, sort: true}
            , {field: 'userCode', title: '用户账号', width: 120}
            , {field: 'createTime', title: '用户注册时间', width: 180}
            , {field: 'state', title: '用户状态', width: 99, templet: '#ACCOUNT_STATUS'}
            , {fixed: 'right', title: '操作', toolbar: '#barDemo'}
        ]]
        , page: true
        , limit: 10
        , limits: [10, 30, 50, 100]
        , request: {
            pageName: 'pageNumber',
            limitName: 'limit'
        }
        , parseData: function (res) { //res 即为原始返回的数据
            return {
                "code": res.returnCode, //解析接口状态
                "msg": res.returnMsg, //解析提示文本
                "count": res.count, //解析数据长度
                "data": res.bean //解析数据列表
            };
        }
    });
    //监听锁定操作
    form.on('checkbox(lockDemo)', function (obj) {
        layer.tips(this.value + ' ' + this.name + '：' + obj.elem.checked, obj.othis);
    });
    var detail;
    //监听行工具事件
    table.on('tool(test)', function (obj) {
        var data = obj.data;
        var userType = data.userType;
        if (obj.event === 'permission') {
            var loadingId = layer.open({type: 4});
            //编辑
            var menuListReq = {};
            menuListReq.userId = data.userId;
            console.log(menuListReq)
            var reqParam = {
                url: "/menu/queryMenuPermission",
                param: menuListReq,
                callback: function (resp) {
                    console.log(detail);
                    layer.open({
                        type: 1,
                        title: '修改角色菜单权限',
                        content: $('#RoleEdit').html(),
                        area: '800px',
                        offset: '25px'
                    });
                    buildMenuList(resp);
                    form.render();
                },
                forceSession: true
            };
            ReqUtil.sendPostReq(reqParam);
        }
    });

    //构建菜单列表
    function buildMenuList(resp) {
        var menuList = resp.bean;
        console.log(menuList)
        if (menuList != null && menuList.length > 0) {
            var hiddenDiv = $('<input/>');
            hiddenDiv.attr("type", "hidden");
            hiddenDiv.attr("name", "userId");
            hiddenDiv.attr("value", resp.userId);
            hiddenDiv.appendTo($("#roleAuthorityDiv"));
            for (var x = 0; x < menuList.length; x++) {
                var menuCatagroyItem = menuList[x];
                var menuItemDiv = $('<div></div>');
                menuItemDiv.addClass('layui-form-item');
                var menuMainDiv = $('<div></div>');
                menuMainDiv.addClass('layui-row');
                menuMainDiv.appendTo(menuItemDiv);
                var menuAuthItemDiv = $('<div></div>');
                menuAuthItemDiv.addClass('layui-row');
                menuAuthItemDiv.appendTo(menuMainDiv);
                var menuLableSecondDiv = $('<label></label>');
                menuLableSecondDiv.addClass('layui-form-label');
                menuLableSecondDiv.appendTo(menuAuthItemDiv);
                var menuInputDiv = $('<div></div>');
                menuInputDiv.addClass('layui-input-block');
                menuInputDiv.appendTo(menuAuthItemDiv);
                var menuCheckboxDiv = $('<input/>');
                menuCheckboxDiv.attr("type", "checkbox");
                menuCheckboxDiv.attr("name", "menuId");
                menuCheckboxDiv.attr("title", menuCatagroyItem.menuName);
                if (menuCatagroyItem.permission == "1") {
                    menuCheckboxDiv.attr("checked", "true");
                    menuCheckboxDiv.attr("value", 'having-' + menuCatagroyItem.menuId);
                }else {
                    menuCheckboxDiv.attr("value", menuCatagroyItem.menuId);
                }
                menuCheckboxDiv.appendTo(menuInputDiv);
                menuItemDiv.appendTo($("#roleAuthorityDiv"));
            }
            var menuButtonItemDiv = $('<div></div>');
            menuButtonItemDiv.addClass('layui-form-item');
            menuButtonItemDiv.attr("align", "left");
            var menuButtonDiv = $('<div></div>');
            menuButtonDiv.addClass('layui-input-block');
            //添加分类div
            menuButtonDiv.attr("align", "right");
            menuButtonDiv.attr("style", "padding-right:80px;");
            menuButtonDiv.appendTo(menuButtonItemDiv);
            var buttonDiv = $('<button></button>');
            buttonDiv.addClass('layui-btn');
            buttonDiv.attr("lay-submit", "");
            buttonDiv.attr("lay-filter", "btnAuthorityEdit");
            buttonDiv.text("保存");
            buttonDiv.appendTo(menuButtonDiv);
            menuButtonItemDiv.appendTo($("#roleAuthorityDiv"));
        }
    }

    //修改权限信息按钮事件
    form.on('submit(btnAuthorityEdit)', function (data) {
        var arr = [];
        $("input:checkbox[name='menuId']:checked").each(function (i) {
            arr[i] = $(this).val();
        });
        data.field.menuId = arr.join(",");//将数组合并成字符串
        var authorityEditReq = data.field;
        console.log(authorityEditReq)
        var loadDialogIndex = layer.load(2);
        var reqParam = {
            url: "/menu/addMenuPermission",
            param: authorityEditReq,
            callback: function (resp) {
                layer.close(loadDialogIndex);
                layer.closeAll();
                layer.msg(resp.returnMsg);
                menuPermission.reload({
                    page: {
                        curr: 1 //重新从第一页开始
                    }
                });
            },
            failed: function (resp) {
                layer.close(loadDialogIndex);
                layer.msg(resp.returnMsg)
            },
            error: function (e) {
                layer.close(loadDialogIndex);
                console.log("接口异常:" + e);
            },
            forceSession: true
        };
        ReqUtil.sendPostReq(reqParam);
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });
    //查询节点按钮事件
    layui.form.on('submit(btnQuery)', function (data) {
        var searchInfo = data.field;
        menuPermission.reload({  // 触发列表重新请求数据//查询
            where: searchInfo,
            page: {
                curr: 1
            }
        });
        return false;
    });

    //修改用户账号状态
    form.on('switch(accountStatus)', function (data) {
        var flag = data.elem.checked; //是否被选中，true或者false
        var value = data.value; //复选框value值，也可以通过data.elem.value得到
        var userType = $(data.elem).attr('userType');
        var accountStatusSwitch = {};
        let state = -1;
        if (flag === false) {
            state = 0;
        }else {
            state = 1;
        }
        accountStatusSwitch.userId = value;
        accountStatusSwitch.state = state;
        console.log(accountStatusSwitch)
        var loadDialogIndex = layer.load(2);
        var reqParam = {
            url: "/user/updateUserState",
            param: accountStatusSwitch,
            callback: function (resp) {
                layer.close(loadDialogIndex);
                layer.msg(resp.returnMsg);
                //重新做一次查询
                menuPermission.reload({  // 触发列表重新请求数据
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
            },
            failed: function (resp) {
                layer.close(loadDialogIndex);
                layer.msg(resp.returnMsg);
                form.render('checkbox');
                menuPermission.reload({
                    page: {
                        curr: 1 //重新从第一页开始
                    }
                });
            },
            error: function (e) {
                layer.close(loadDialogIndex);
                console.log("接口异常:" + e);
            },
            forceSession: true
        };
        ReqUtil.sendPostReq(reqParam);
        form.render('checkbox');
    });
});